package collector

import (
	"database/sql"
	"log/slog"

	"github.com/prometheus/client_golang/prometheus"
)

const (
	// Scrape query.
	tableSpaceQuery = `select name,used_size * page used_size,t2.max_size from v$tablespace t1,(select group_id,sum(max_size) max_size from v$datafile group by group_id) t2 where t1.id=t2.group_id and t1.name!='TEMP' union select name,used_size * page,max_size*page/1024/1024 from v$tablespace  where name='TEMP'	`

	// Subsystem.
	tableSpace = "table_space"
)

var (
	tableSpaceDesc = prometheus.NewDesc(
		prometheus.BuildFQName(namespace, tableSpace, "tablespaces"),
		"The storage of each  tablespace in the DM",
		[]string{"space", "index"}, nil,
	)
)

type TableSpace struct {
}

func (TableSpace) Name() string {
	return "tableSpace"
}
func (TableSpace) Scrape(db *sql.DB, ch chan<- prometheus.Metric, backupPath string, logger *slog.Logger) error {

	var (
		name string
		//thread_desc string
		used_size float64 //unit KB
		max_size  float64 //unit MB
	)
	tableSpaceRows, err := db.Query(tableSpaceQuery)
	if err != nil {
		logger.Error("Failed to query tablespace", "error", err)
		return err
	}
	defer tableSpaceRows.Close()
	for tableSpaceRows.Next() {
		if err := tableSpaceRows.Scan(&name, &used_size, &max_size); err != nil {
			logger.Error("Failed to scan tablespace row", "error", err)
			return err
		}
		ch <- prometheus.MustNewConstMetric(
			tableSpaceDesc, prometheus.GaugeValue, used_size,
			name, "used_size",
		)
		ch <- prometheus.MustNewConstMetric(
			tableSpaceDesc, prometheus.GaugeValue, max_size,
			name, "max_size",
		)

	}

	return nil
}

func init() {
	RegisterScraper("tableSpace", TableSpace{})
}

var _ Scraper = TableSpace{}
